﻿#include <iostream>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#define BUF_SIZE 1024
void ErrorHandle(const char *message);
int main(int argc, char *argv[])
{
  int sock_serv, sock_clnt;
  // step01:创建套接字
  sock_serv = socket(PF_INET, SOCK_STREAM, 0);
  struct sockaddr_in addr_serv
  {
  };
  // step02：给套接字设置IP和端口号
  addr_serv.sin_family = AF_INET;
  addr_serv.sin_addr.s_addr = htonl(INADDR_ANY);
  addr_serv.sin_port = htons(atoi(argv[1]));
  auto bind_result = bind(sock_serv, (sockaddr *)&addr_serv, sizeof(addr_serv));
  if (bind_result == -1)
    ErrorHandle("bind() error!");
  std::cout << "bind() ok..." << std::endl;
  // step03：转入等待连接请求状态
  auto listen_result = listen(sock_serv, 5);
  if (listen_result == -1)
    ErrorHandle("listen() error!");
  std::cout << "listen() ok..." << std::endl;

  sockaddr_in addr_clnt;
  socklen_t size_addr_clnt = sizeof(addr_clnt);
  int i = 0;
  while (i < 5)
  {
    // step04：接收请求连接
    sock_clnt = accept(sock_serv, (sockaddr *)&addr_clnt, &size_addr_clnt);
    if (sock_clnt == -1)
      ErrorHandle("accept() error!");
    std::cout << "connected client " << i << std::endl;
    char message[BUF_SIZE];
    int strlen{0};
    while ((strlen = read(sock_clnt, message, BUF_SIZE) != 0))
    {
      std::cout << "Receive message from client: " << message << std::endl;
      write(sock_clnt, "ok", sizeof("ok"));
      strcpy(message, "");
    }
    close(sock_clnt);
    ++i;
  }

  close(sock_serv);
  return 0;
}
void ErrorHandle(const char *message)
{
  std::cout << message << std::endl;
  exit(-1);
}